package com.example.drainage.ui.calendar

import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs

/**
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.example.drainage.ui.calendar
 * @createTime 创建时间 ：2021/11/25
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
object SchedulingCalendarUtil {

    private val sdf = SimpleDateFormat("yyyy-MM", Locale.CHINA)

    private val calCalendar = Calendar.getInstance()

    private val selectCalendar = Calendar.getInstance()

    fun calMonthsBetweenCalendar(before: Calendar, after: Calendar): Int {
        val result: Int = after.get(Calendar.MONTH) - before.get(Calendar.MONTH)
        val month: Int = (after.get(Calendar.YEAR) - before.get(Calendar.YEAR)) * 12
        return abs(month + result)
    }

    fun getTimeStrFromMonthIndex(position: Int): String {
        calCalendar.set(1970, 0, 1)
        calCalendar.add(Calendar.MONTH, position)
        return sdf.format(calCalendar.time)
    }

    fun getCurMonthCalendar(position: Int): Calendar {
        calCalendar.set(1970, 0, 1)
        calCalendar.add(Calendar.MONTH, position)
        return calCalendar
    }

    fun getNowMonthIndex(): Int {
        val curTimeCalendar = Calendar.getInstance()
        calCalendar.set(1970, 0, 1)
        return calMonthsBetweenCalendar(calCalendar, curTimeCalendar)
    }

    fun getDayListFromMonthIndex(position: Int): MutableList<CalendarBean> {
        calCalendar.set(1970, 0, 1)
        calCalendar.add(Calendar.MONTH, position)
        val dayList = mutableListOf<CalendarBean>()
        val year = calCalendar.get(Calendar.YEAR)
        val month = calCalendar.get(Calendar.MONTH) + 1
        val emptyDayCount = calCalendar.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY - 1
        for (i in 0..emptyDayCount) {
            dayList.add(CalendarBean())
        }
        val dayCount = getDaysOfMonth(year, month)
        for (i in 1..dayCount) {
            dayList.add(CalendarBean(year, month, i))
        }
        return dayList
    }

    /**
     * 根据传入的年份和月份，判断当前月有多少天
     *
     * @param year
     * @param month
     * @return
     */
    fun getDaysOfMonth(year: Int, month: Int): Int {
        when (month) {
            1, 3, 5, 7, 8, 10, 12 -> return 31
            2 -> return if (isLeap(year)) {
                29
            } else {
                28
            }
            4, 6, 9, 11 -> return 30
        }
        return -1
    }

    /**
     * 判断是否为闰年
     *
     * @param year
     * @return
     */
    fun isLeap(year: Int): Boolean {
        return year % 4 == 0 && year % 100 != 0 || year % 400 == 0
    }

    fun getSelectCalendar(): Calendar {
        return selectCalendar
    }

    fun updateSelectCalendar(year: Int, month: Int, day: Int) {
        selectCalendar.set(year, month, day)
    }
}